package kr.co.sdsway2.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import kr.co.sdsway2.common.AbstractService;
import kr.co.sdsway2.vo.PollAswInfVO;

import org.springframework.stereotype.Service;

@Service
public class PollAswInfBeanService extends AbstractService {

	@Resource(name="pollAswInfBeanList")
	private List<PollAswInfVO> pollAswInfBeanList;

	/** 새로운 POLL ASW 입력 */
	public int insertPollAswInfBean(Integer ptId,Integer pollId,String avatarId,String aswVal) {
		if(getIndex(ptId,pollId,avatarId)<0){ //없을때만 insert
			PollAswInfVO vo = new PollAswInfVO();
			vo.setPtId(ptId);
			vo.setPollId(pollId);
			vo.setAvatarId(avatarId);
			vo.setAswVal(aswVal);
			
			pollAswInfBeanList.add(vo);
			return 1;	//성공
		}else{
			return 0;	//실패
		}
	}

	/** POLL ASW 삭제(by ID) 서비스 */
	public void remove(Integer ptId,Integer pollId,String avatarId) {
		int idx = getIndex(ptId,pollId,avatarId);
		if( idx != -1 ) this.pollAswInfBeanList.remove(idx);
	}

	/** POLL ASW 삭제(by index) 서비스 */
	public void remove(int idx){
		this.pollAswInfBeanList.remove(idx);
	}

	/** POLL ASW 목록 조회 서비스 */
	public List<PollAswInfVO> getList(){
		return this.pollAswInfBeanList;
	}
	
	/** POLL ASW 목록 조회 서비스 */
	public List<PollAswInfVO> getList(Integer pollId){
		List<PollAswInfVO> list = new ArrayList<PollAswInfVO>();
		for(PollAswInfVO vo : pollAswInfBeanList){
			if(pollId.equals(vo.getPollId())) list.add(vo);
		}
		return list;
	}

	/** POLL ASW 조회 서비스 */
	public PollAswInfVO getPollAswInfBean(Integer ptId,Integer pollId,String avatarId) {
		int i = getIndex(ptId,pollId,avatarId);
		if(i>=0){
			return pollAswInfBeanList.get(i);
		}
		return null;
	}

	/** POLL ASW 상태 변경 서비스 */
	public int update(Integer ptId,Integer pollId,String avatarId,String aswVal){
		PollAswInfVO vo = null;
		int i = getIndex(ptId,pollId,avatarId);
		if(i<0){
			insertPollAswInfBean(ptId, pollId,avatarId,aswVal);
			i = getIndex(ptId,pollId,avatarId);
		}
		if(i>=0){
			vo = pollAswInfBeanList.get(i);
			vo.setAswVal(aswVal);
			return 1;
		}
		return 0;
	}

	/** POLL ASW ID 통해 index 획득 */
	private int getIndex(Integer ptId,Integer pollId,String avatarId){
		int idx = -1;
		int size = pollAswInfBeanList.size();
		PollAswInfVO vo;
		for(int i=0;i<size;i++){
			vo = pollAswInfBeanList.get(i);
			if(vo!=null && vo.getPtId()!=null && vo.getPollId()!= null && vo.getAvatarId()!= null){
				if(vo.getPtId().equals(ptId) && vo.getPollId().equals(pollId) && vo.getAvatarId().equals(avatarId))
					idx = i;
			}
		}
		return idx;
	}
	
}
